package com.group7.mall.service.impl;

import com.group7.mall.convert.UserAddressConverter;
import com.group7.mall.dao.TbUserAddressDao;
import com.group7.mall.dto.UserAddressDto;
import com.group7.mall.entity.TbUser;
import com.group7.mall.entity.TbUserAddress;
import com.group7.mall.service.UserAddressService;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserAddressServiceImpl implements UserAddressService {
    @Resource
    private TbUserAddressDao tbUserAddressDao;

    @Override
    public List<UserAddressDto> queryAllUserAddress(String userOpenId) {
        List<TbUserAddress> tbUserAddressList = tbUserAddressDao.queryListByUserId(userOpenId);
        return UserAddressConverter.INSTANCE.convertTbtUserAddressToUserAddressDto(tbUserAddressList);
    }

    @Override
    public Integer changeDefaultAddress(UserAddressDto userAddressDto) {
        TbUserAddress tbUserAddress = UserAddressConverter.INSTANCE.convertUserAddressDtoToTbUserAddress(userAddressDto);
        return tbUserAddressDao.changeDefaultAddress(tbUserAddress);
    }

    @Override
    public UserAddressDto insert(UserAddressDto userAddressDto) {
        TbUserAddress tbUserAddress = UserAddressConverter.INSTANCE.convertUserAddressDtoToTbUserAddress(userAddressDto);
        tbUserAddressDao.insert(tbUserAddress);
        if(userAddressDto.getIsDefault() == 1) {
            tbUserAddressDao.changeDefaultAddress(tbUserAddress);
        }
        return UserAddressConverter.INSTANCE.converTbUserAddressToUserAddressDto(tbUserAddress);
    }

    @Override
    public UserAddressDto update(UserAddressDto userAddressDto) {
        TbUserAddress tbUserAddress = UserAddressConverter.INSTANCE.convertUserAddressDtoToTbUserAddress(userAddressDto);
        if(tbUserAddressDao.update(tbUserAddress) == 0) {
            return null;
        }
        return UserAddressConverter.INSTANCE.converTbUserAddressToUserAddressDto(tbUserAddress);
    }

    @Override
    public int deleteById(Integer id) {
        return tbUserAddressDao.deleteById(id);
    }

    @Override
    public UserAddressDto showOneAddress(UserAddressDto userAddressDto) {
        TbUserAddress tbUserAddress = tbUserAddressDao.queryById(userAddressDto.getAddressId());
        return UserAddressConverter.INSTANCE.converTbUserAddressToUserAddressDto(tbUserAddress);
    }

    @Override
    public Integer queryDefaultAddressId(TbUser tbUser) {
        return tbUserAddressDao.queryUserDefaultAddress(tbUser).getAddressId();
    }
}
